package Zadanie7;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class ThreadClientServer extends Thread {
	
	private Socket incoming;
	private int counter;
	
	ThreadClientServer(Socket i, int c) {
		
		incoming = i;
		counter = c;
		
	}
	
	public void run() {
		
		InputStream is = null;
		OutputStream os = null;
		
		
			
			
			try {
				
				is = incoming.getInputStream();  
				os = incoming.getOutputStream();
				
	        } catch (UnknownHostException e) {
	            System.err.println("Don't know about host: hostname");
	        } catch (IOException e) {
	            System.err.println("Couldn't get I/O for the connection to: hostname");
	        }
				
	    
	         if (os != null && is != null) {
	                 try {
	                
	                ObjectOutputStream oos = new ObjectOutputStream(os);  	 
	                ObjectInputStream ois = new ObjectInputStream(is); 
	                
	                while(!Server.isEnd)	  {
	
	                    oos.writeObject(Server.getVector(Server.A, Server.B));
	  
	                    VectorM vector = (VectorM) ois.readObject();
	                  
	                    System.out.println("(Serwer) obliczanie macierzy BA : proces  " + counter + " aktualna suma : " + vector.sum);
	                    
	                    Server.addToMatrix(vector, Server.AB);
	                  
	                    vector = null;
	        
	                    
	                } 
	                
	              
	                
	                Server.reset();
	                
	                while(!Server.isEnd)	  {
	                	
	                    oos.writeObject(Server.getVector(Server.AB, Server.C));
	                    Server.increment();
	
	                    VectorM vector = (VectorM) ois.readObject();
	                    System.out.println("Serwer macierz C - sum dla counter " + counter + ": " + vector.sum);
	                  
	                    
	                    Server.addToMatrix(vector, Server.D);

	                    vector = null;
	                    
	                   
	                } 
	                
	     
	              
	                 } catch (UnknownHostException e) {
	                     System.err.println("Trying to connect to unknown host: " + e);
	                 } catch (IOException e) {
	                     System.err.println("IOException:  " + e);
	                 } catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	             }
	         	Server.decrementTaskCounter();
	         } 	
		
		
		
	

}
